package com.itawei.d7_threadsafe;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyRunnable implements Runnable {
    int ticket = 0;
    static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        //卖一百张电影票
        //1.循环
        while (true) {
            //2.同步代码块
//            synchronized (MyRunnable.class) {
            lock.lock();
            try {
                //3.判断共享数据是否到末尾 到了
                if (ticket == 100) {
                    break;
                } else {
                    //4.判断共享数据是否到末尾 没到
                    ticket++;
                    System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");

                }
//            }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();//停不了程序 try catch
            }

        }
    }


}
